package com.emn.fil.automaticdiscover.dto.pingjpc;

import javax.swing.event.EventListenerList;

import jpcap.JpcapCaptor;
import jpcap.packet.ARPPacket;
import jpcap.packet.ICMPPacket;
import jpcap.packet.Packet;

public class PacketReceiver implements Runnable{
	private JpcapCaptor captor;
	private EventListenerList listeners = new EventListenerList();	
	
	public PacketReceiver(JpcapCaptor captor){
		this.captor = captor;
	}	

	public void addARPListener( IARPPacketListener listener ) {
		listeners.add( IARPPacketListener.class, listener );
	}
	
	public void removeARPListener( IARPPacketListener listener ){
		listeners.remove( IARPPacketListener.class, listener );
	}

	protected synchronized void notifyARPListeners( ARPPacketArrivedEvent event )  {
		for ( IARPPacketListener l : listeners.getListeners( IARPPacketListener.class )){
			l.arpPacketArrived(event);
		}
	} 
	
	public void addICMPListener( IICMPPacketListener listener ) {
		listeners.add( IICMPPacketListener.class, listener );
	}
	
	public void removeICMPListener( IICMPPacketListener listener ){
		listeners.remove( IICMPPacketListener.class, listener );
	}

	protected synchronized void notifyICMPListeners( ICMPPacketArrivedEvent event )  {
		for ( IICMPPacketListener l : listeners.getListeners( IICMPPacketListener.class )){
			l.icmpPacketArrived(event);
		}
	} 
	
	public void run(){
		while(true){
			Packet packet = captor.getPacket();
			if(packet instanceof ARPPacket){
				ARPPacket arpPacket = (ARPPacket)packet;
				notifyARPListeners(new ARPPacketArrivedEvent(this,arpPacket));
			}
			if(packet instanceof ICMPPacket){
				ICMPPacket icmpPacket = (ICMPPacket)packet;
				notifyICMPListeners(new ICMPPacketArrivedEvent(this,icmpPacket));
			}
		}
	}

}
